package dao;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Locale;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DatabaseHelper extends SQLiteOpenHelper{

	private static String DATABASE_PATH = "/data/data/com.example.surveyapplication/databases/";
	private static String DATABASE_NAME = "SurveyDatabase";
	private Context myContext;
	static SQLiteDatabase myDataBase;
	
	public DatabaseHelper(Context context) {
		super(context, DATABASE_NAME, null, 1);
		// TODO Auto-generated constructor stub
		this.myContext = context;
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// TODO Auto-generated method stub
		
	}

	String path = DATABASE_PATH + DATABASE_NAME;
	public void checkAndCopyDatabase() throws IOException {
		boolean dbExist = checkDataBase();
		if (dbExist) {
			//copyDataBase();
			Log.d("TAG", "database already exist!");
		} else {
			this.getReadableDatabase();
			try {
				copyDataBase();
			} catch (IOException e) {
				Log.d("TAG", "Error copying database");
			}
		}
		close();
	}

	private boolean checkDataBase() {
//		SQLiteDatabase checkDB = null;
//		try {
//			checkDB = SQLiteDatabase.openDatabase(path, null,
//					SQLiteDatabase.OPEN_READWRITE);
//		} catch (SQLiteException e) {
//		}
//		if (checkDB != null)
//			checkDB.close();
//		return checkDB != null ? true : false;
		File dbFile = new File(path);
		return dbFile.exists();
	}
	
	private void copyDataBase() throws IOException {
		InputStream myInput = myContext.getAssets().open("surveyapplication.db");
		OutputStream myOutput = new FileOutputStream(path);
		byte[] buffer = new byte[1024];
		int length;
		while ((length = myInput.read(buffer)) > 0) {
			myOutput.write(buffer, 0, length);
		}
		myOutput.flush();
		myOutput.close();
		myInput.close();
	}

	protected static Object getDataRowFromDataReader(Cursor cursor) {
		return null;
	}

	public void open() {
		try {
			myDataBase = SQLiteDatabase.openDatabase(path, null,
					SQLiteDatabase.OPEN_READWRITE);
			if (!myDataBase.isOpen()) {
				myDataBase.setLocale(new Locale("en_US"));
			}

		} catch (SQLiteException ex) {
			ex.printStackTrace();
			Log.i("aaa", "There is no valid dictionary database " + " at path ");
		}
	}

	@Override
	public void close() {
		if (myDataBase != null)
			myDataBase.close();
		super.close();
	}
}
